package com.promise.jokerdream.ui.tower

import androidx.activity.compose.BackHandler
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.compose.ui.platform.LocalContext
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.windowInsetsPadding
import com.promise.jokerdream.database.UserDataManager
import com.promise.jokerdream.model.log.ExecutionLog
import com.promise.jokerdream.ui.components.LogItem
import com.promise.jokerdream.ui.components.RoundCheckbox
import com.promise.jokerdream.ui.theme.AppFontSizes
import com.promise.jokerdream.ui.theme.AppSpacing
import com.promise.jokerdream.ui.toolbar.AppTopBar
import com.promise.jokerdream.viewmodel.FightTowerViewModel

/**
 * 斗神塔挑战页面
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FightTowerPage(
    modifier: Modifier = Modifier,
    onBackClick: () -> Unit
) {
    val context = LocalContext.current
    val userDataManager = remember { UserDataManager.getInstance(context) }
    val currentAccount = remember { userDataManager.getCurrentAccount() }
    val userConfig = remember { currentAccount?.config }
    
    val viewModel: FightTowerViewModel = viewModel { 
        FightTowerViewModel().apply {
            currentAccount?.userId?.let { setUserId(it) }
        }
    }
    
    val uiState by viewModel.uiState.collectAsState()

    // 处理返回键
    BackHandler {
        onBackClick()
    }
    
    // 页面加载时自动获取斗神塔数据
    LaunchedEffect(Unit) {
        viewModel.loadTowerData()
    }
    
    Column(
        modifier = modifier.fillMaxSize()
    ) {
        // 顶部导航栏
        AppTopBar(
            title = "斗神塔",
            onBackClick = onBackClick
        )
        
        // 当前状态卡片（固定）
        TowerStatusCard(
            towerData = uiState.towerData,
            modifier = Modifier.padding(AppSpacing.pageHorizontal)
        )
        
        // 操作记录区域（可滚动）
        LazyColumn(
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
                .background(MaterialTheme.colorScheme.background),
            contentPadding = PaddingValues(horizontal = AppSpacing.pageHorizontal)
        ) {
            item {
                // 操作记录
                TowerExecutionLogs(
                    logs = uiState.executionLogs
                )
            }
            
            // 底部间距
            item {
                Spacer(modifier = Modifier.height(AppSpacing.bottomSafeArea))
            }
        }
        
        // 固定在底部的操作控制卡片
        TowerActionButtons(
            towerData = uiState.towerData,
            isTaskRunning = uiState.isTaskRunning,
            sundayUseUpCount = uiState.sundayUseUpCount,
            onSundayUseUpCount = { viewModel.toggleSundayUseUpCount() },
            onOneClickExecute = { viewModel.startOneClickTask() },
            onCancelTask = { viewModel.stopCurrentTask() }
        )
    }
}

/**
 * 斗神塔状态卡片
 */
@Composable
private fun TowerStatusCard(
    towerData: com.promise.jokerdream.response.phone.FightTowerXmlResponse?,
    modifier: Modifier = Modifier
) {
    // 战斗剩余时间倒计时
    var remainingTime by remember { mutableStateOf(towerData?.remainingBattleTime ?: 0) }
    
    // 当towerData变化时更新remainingTime
    LaunchedEffect(towerData?.remainingBattleTime) {
        remainingTime = towerData?.remainingBattleTime ?: 0
    }
    
    Card(
        modifier = modifier.fillMaxWidth(),
        shape = RoundedCornerShape(12.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer
        )
    ) {
        Column(
            modifier = Modifier.padding(16.dp)
        ) {
            Text(
                text = "当前状态",
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onPrimaryContainer
            )
            
            Spacer(modifier = Modifier.height(12.dp))
            
            if (towerData != null) {
                // 当前层数和分数在同一行
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    // 左侧：当前层数
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "当前层数:",
                            fontSize = AppFontSizes.mediumBody,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "第${towerData.currentFloor}层",
                            fontSize = AppFontSizes.mediumBody,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                    
                    // 右侧：当前分数
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = "当前分数:",
                            fontSize = AppFontSizes.mediumBody,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                        Spacer(modifier = Modifier.width(4.dp))
                        Text(
                            text = "${towerData.currentScore}分",
                            fontSize = AppFontSizes.mediumBody,
                            fontWeight = FontWeight.Medium,
                            color = MaterialTheme.colorScheme.onPrimaryContainer
                        )
                    }
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 战斗剩余时间
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "战斗剩余时间:",
                        fontSize = AppFontSizes.mediumBody,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                    Text(
                        text = "${remainingTime}秒",
                        fontSize = AppFontSizes.mediumBody,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }
                
                Spacer(modifier = Modifier.height(8.dp))
                
                // 今日剩余次数和本周付费次数
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    // 今日剩余次数
                    Text(
                        text = "今日剩余次数: ${towerData.todayRemainingCount}/${towerData.todayTotalCount}",
                        fontSize = AppFontSizes.mediumBody,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                    
                    // 本周付费次数
                    Text(
                        text = "本周付费次数: ${towerData.weeklyPaidCount}/${towerData.weeklyPaidTotalCount}",
                        fontSize = AppFontSizes.mediumBody,
                        color = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                }
            } else {
                Text(
                    text = "暂无数据",
                    fontSize = AppFontSizes.mediumBody,
                    color = MaterialTheme.colorScheme.onPrimaryContainer
                )
            }
        }
    }
}


/**
 * 操作按钮区域
 */
@Composable
private fun TowerActionButtons(
    towerData: com.promise.jokerdream.response.phone.FightTowerXmlResponse?,
    isTaskRunning: Boolean,
    sundayUseUpCount: Boolean,
    onSundayUseUpCount: (Boolean) -> Unit,
    onOneClickExecute: () -> Unit,
    onCancelTask: () -> Unit,
    modifier: Modifier = Modifier
) {
    Surface(
        modifier = modifier.fillMaxWidth(),
        color = MaterialTheme.colorScheme.surface,
        shadowElevation = 8.dp
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(
                    horizontal = AppSpacing.pageHorizontal,
                    vertical = AppSpacing.pageVertical
                ),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            // 左侧：周日用完次数
            Row(
                modifier = Modifier.clickable { onSundayUseUpCount(!sundayUseUpCount) },
                verticalAlignment = Alignment.CenterVertically
            ) {
                RoundCheckbox(
                    checked = sundayUseUpCount,
                    onCheckedChange = { 
                        onSundayUseUpCount(it)
                    },
                    size = 20.dp
                )
                Spacer(modifier = Modifier.width(8.dp))
                Text(
                    text = "周日用完次数",
                    fontSize = AppFontSizes.mediumBody,
                    color = MaterialTheme.colorScheme.onSurface
                )
            }
            
            // 右侧：一键执行按钮
            Button(
                onClick = if (isTaskRunning) onCancelTask else onOneClickExecute,
                enabled = towerData != null,
                modifier = Modifier.width(120.dp),
                colors = if (isTaskRunning) {
                    ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                } else {
                    ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primary
                    )
                }
            ) {
                Text(
                    text = if (isTaskRunning) "停止执行" else "一键执行",
                    fontSize = AppFontSizes.body,
                    fontWeight = FontWeight.Bold
                )
            }
        }
        
        // 底部安全区域
        Spacer(
            modifier = Modifier
                .fillMaxWidth()
                .windowInsetsPadding(WindowInsets.navigationBars)
                .height(0.dp)
        )
    }
}

/**
 * 操作记录
 */
@Composable
private fun TowerExecutionLogs(
    logs: List<ExecutionLog>
) {
    if (logs.isNotEmpty()) {
        // 操作记录列表
        Column(
            modifier = Modifier.fillMaxWidth(),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            logs.forEach { log ->
                LogItem(log = log)
            }
        }
    }
}
